using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Acme.BookStore.Domain.Entities;
using Acme.BookStore.Kehus.Dtos;
using Acme.BookStore.Permissions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using System.Linq;
using Microsoft.Extensions.Caching.Distributed;
using Volo.Abp.Caching;
using System.Text.Json;

namespace Acme.BookStore.Kehus
{
    //[Authorize(BookStorePermissions.Kehus.Default)]
    public class KehuAppService : ApplicationService, IKehuAppService
    {
        private readonly IKehuRepository _kehuRepository;
        private readonly IDistributedCache<List<KehuDto>> _kehuCache;

        public KehuAppService(
            IKehuRepository kehuRepository,
            IDistributedCache<List<KehuDto>> kehuCache)
        {
            _kehuRepository = kehuRepository;
            _kehuCache = kehuCache;
        }

        public async Task<KehuDto> GetAsync(string id)
        {
            // 尝试从缓存获取单个客户信息
            var cacheKey = $"Kehu:{id}";
            var kehuDtoList = await _kehuCache.GetOrAddAsync(
                cacheKey,
                async () =>
                {
                    var kehu = await _kehuRepository.GetAsync(id);
                    var kehuDto = ObjectMapper.Map<Kehu, KehuDto>(kehu);
                    return new List<KehuDto> { kehuDto };
                },
                () => new DistributedCacheEntryOptions
                {
                    AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(30)
                }
            );

            return kehuDtoList.FirstOrDefault();
        }

        public async Task<PagedResultDto<KehuDto>> GetListAsync(PagedAndSortedResultRequestDto input)
        {
            var totalCount = await _kehuRepository.GetCountAsync(null);

            // 为分页查询构建缓存键
            var cacheKey = $"Kehus:List:{input.SkipCount}:{input.MaxResultCount}:{input.Sorting ?? "Id"}";
            
            var kehuDtos = await _kehuCache.GetOrAddAsync(
                cacheKey,
                async () =>
                {
                    var kehus = await _kehuRepository.GetListAsync(
                        input.SkipCount,
                        input.MaxResultCount,
                        input.Sorting ?? "Id",
                        null);

                    return ObjectMapper.Map<List<Kehu>, List<KehuDto>>(kehus);
                },
                () => new DistributedCacheEntryOptions
                {
                    AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(10)
                }
            );

            return new PagedResultDto<KehuDto>(totalCount, kehuDtos);
        }

        [HttpGet("api/app/kehu/search")]
        public async Task<PagedResultDto<KehuDto>> GetListAsync(KehuSearchDto input)
        {
            // 对于搜索条件，不进行缓存，因为搜索条件多变
            var totalCount = await _kehuRepository.GetCountAsync(
                input.Filter,
                input.Name,
                input.ContactPerson,
                input.Phone,
                input.Mobile,
                input.EnterpriseAttribute
            );

            var kehus = await _kehuRepository.GetListAsync(
                input.SkipCount,
                input.MaxResultCount,
                input.Sorting ?? "Id",
                input.Filter,
                input.Name,
                input.ContactPerson,
                input.Phone,
                input.Mobile,
                input.EnterpriseAttribute
            );

            var kehuDtos = ObjectMapper.Map<List<Kehu>, List<KehuDto>>(kehus);

            return new PagedResultDto<KehuDto>(totalCount, kehuDtos);
        }
        
        [HttpGet("api/app/kehu/search-by-name")]
        public async Task<PagedResultDto<KehuDto>> SearchByNameAsync(KehuNameSearchDto input)
        {
            // 按名称关键词搜索也不进行缓存
            var totalCount = await _kehuRepository.GetCountByNameAsync(input.NameKeyword);

            var kehus = await _kehuRepository.SearchByNameAsync(
                input.SkipCount,
                input.MaxResultCount,
                input.Sorting ?? "Id",
                input.NameKeyword
            );

            var kehuDtos = ObjectMapper.Map<List<Kehu>, List<KehuDto>>(kehus);

            return new PagedResultDto<KehuDto>(totalCount, kehuDtos);
        }

        //[Authorize(BookStorePermissions.Kehus.Create)]
        public async Task<KehuDto> CreateAsync(CreateKehuDto input)
        {
            // 使用GUID作为客户编码
            var id = Guid.NewGuid().ToString("N");
            
            // 使用构造函数创建实体
            var kehu = new Kehu(id)
            {
                Name = input.Name,
                Address = input.Address,
                ContactPerson = input.ContactPerson,
                Phone = input.Phone,
                Mobile = input.Mobile,
                Contact1 = input.Contact1,
                EnterpriseAttribute = input.EnterpriseAttribute,
                ContractNumber = input.ContractNumber,
                Phone1 = input.Phone1,
                EmailAddress = input.EmailAddress,
                Remarks = input.Remarks
            };

            await _kehuRepository.InsertAsync(kehu);

            // 创建后清除相关缓存
            await _kehuCache.RemoveAsync($"Kehus:List:");

            return ObjectMapper.Map<Kehu, KehuDto>(kehu);
        }

        //[Authorize(BookStorePermissions.Kehus.Edit)]
        public async Task<KehuDto> UpdateAsync(string id, CreateKehuDto input)
        {
            var kehu = await _kehuRepository.GetAsync(id);

            kehu.Name = input.Name;
            kehu.Address = input.Address;
            kehu.ContactPerson = input.ContactPerson;
            kehu.Phone = input.Phone;
            kehu.Mobile = input.Mobile;
            kehu.Contact1 = input.Contact1;
            kehu.EnterpriseAttribute = input.EnterpriseAttribute;
            kehu.ContractNumber = input.ContractNumber;
            kehu.Phone1 = input.Phone1;
            kehu.EmailAddress = input.EmailAddress;
            kehu.Remarks = input.Remarks;

            await _kehuRepository.UpdateAsync(kehu);
            
            // 更新后清除相关缓存
            await _kehuCache.RemoveAsync($"Kehu:{id}");
            await _kehuCache.RemoveAsync($"Kehus:List:");

            return ObjectMapper.Map<Kehu, KehuDto>(kehu);
        }

        //[Authorize(BookStorePermissions.Kehus.Delete)]
        public async Task DeleteAsync(string id)
        {
            await _kehuRepository.DeleteAsync(id);
            
            // 删除后清除相关缓存
            await _kehuCache.RemoveAsync($"Kehu:{id}");
            await _kehuCache.RemoveAsync($"Kehus:List:");
        }
    }
} 